<template>
  <div class="app-container home">
    <!-- 系统概览 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :xs="24" :sm="12" :lg="6" v-for="(item, index) in statsData" :key="index">
        <el-card shadow="hover" class="stat-card" @click="handleStatCardClick(item.label)">
          <div class="card-content">
            <div class="icon-wrapper" :style="{ backgroundColor: item.color }">
              <component :is="item.icon" style="font-size: 24px;color: white" />
            </div>
            <div class="text-wrapper">
              <div class="value">{{ item.value }}</div>
              <div class="label">{{ item.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 核心功能模块 -->
    <el-row :gutter="20">
      <!-- 会议室快速预订 -->
      <el-col :xs="24" :lg="12">
        <el-card class="function-card">
          <template #header>
            <div class="card-header">
              <span class="header-title">快速预订</span>
              <el-button type="primary" link @click="goToBooking">查看更多会议室</el-button>
            </div>
          </template>
          <el-form :model="quickBookForm" label-width="80px">
            <el-form-item label="会议室">
              <el-select v-model="quickBookForm.roomId" placeholder="请选择会议室">
                <el-option v-for="room in meetingRooms" :key="room.id" :label="room.name" :value="room.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="开始时间">
              <el-date-picker v-model="quickBookForm.startTime" type="datetime" placeholder="选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate"
                :disabled-hours="disabledHours" :disabled-minutes="disabledMinutes" />
            </el-form-item>

            <el-form-item label="结束时间">
              <el-date-picker v-model="quickBookForm.endTime" type="datetime" placeholder="选择结束时间"
                value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate"
                :disabled-hours="disabledHours" :disabled-minutes="disabledMinutes" :picker-options="endTimeOptions" />
            </el-form-item>

            <el-button type="primary" @click="handleQuickBook">立即预订</el-button>
          </el-form>
        </el-card>
      </el-col>

      <!-- 订单状态概览 -->
      <el-col :xs="24" :lg="12">
        <el-card class="function-card">
          <template #header>
            <div class="card-header">
              <span class="header-title">我的订单</span>
              <el-button type="primary" link @click="goToOrders">查看全部订单</el-button>
            </div>
          </template>
          <el-table :data="recentOrders" style="width: 100%">
            <el-table-column prop="roomName" label="会议室" />
            <el-table-column prop="date" label="日期" width="200" />
            <el-table-column prop="time" label="时间段" width="300" />
            <el-table-column prop="status" label="状态" width="200">
              <template #default="scope">
                <dict-tag :options="order_status" :value="scope.row.status" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据统计 -->
    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <span class="header-title">会议室使用统计（最近7天）</span>
          </template>
          <div ref="usageChart" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  Calendar,
  Coin,
  OfficeBuilding,
  DocumentChecked
} from '@element-plus/icons-vue'

import { ElMessage } from 'element-plus'
import { getAllMeetingRooms, getOrderList } from "@/api/login"
import { getUnpaidOrderAmount, reserveMeetingroom } from "@/api/system/meetingroom"
const { proxy } = getCurrentInstance()
const { order_status, payment_status } = proxy.useDict('order_status')

const router = useRouter()

// 快速预订表单
const quickBookForm = ref({
  roomId: null,
  startTime: '',
  endTime: ''
})

// 处理统计卡片点击
const handleStatCardClick = (label) => {
  if (label === '总会议室' || label === '可用会议室') {
    router.push('/meetingroom/meetingroom')
  } else if (label === '待付款金额') {
    router.push('/order/order')
  }
}

// 结束时间选择器的选项
const endTimeOptions = computed(() => {
  return {
    disabledDate: (time) => {
      if (!quickBookForm.value.startTime) return false
      const startDate = new Date(quickBookForm.value.startTime)
      return time.getTime() < startDate.getTime() - 8.64e7
    },
    disabledHours: () => {
      if (!quickBookForm.value.startTime) return []
      const startDate = new Date(quickBookForm.value.startTime)
      const currentHour = startDate.getHours()
      return Array.from({ length: currentHour }, (_, i) => i)
    },
    disabledMinutes: (hour) => {
      if (!quickBookForm.value.startTime) return []
      const startDate = new Date(quickBookForm.value.startTime)
      if (hour === startDate.getHours()) {
        return Array.from({ length: startDate.getMinutes() }, (_, i) => i)
      }
      return []
    }
  }
})

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const disabledHours = () => {
  const now = new Date()
  return Array.from({ length: now.getHours() }, (_, i) => i)
}

const disabledMinutes = (hour) => {
  const now = new Date()
  if (hour === now.getHours()) {
    return Array.from({ length: now.getMinutes() }, (_, i) => i)
  }
  return []
}

// 统计数据卡片
const statsData = ref([
  { icon: OfficeBuilding, label: '总会议室', value: '', color: '#409EFF' },
  { icon: Coin, label: '可用会议室', value: '', color: '#67C23A' },
  { icon: DocumentChecked, label: '待付款金额', value: '¥0.00', color: '#E6A23C' },
  { icon: Calendar, label: '会议室使用率', value: '82%', color: '#F56C6C' }
])

const meetingRooms = ref([])
const recentOrders = ref([])
const usageChart = ref(null)

// 初始化
onMounted(() => {
  initChart()
  fetchMeetingRoomStats()
  fetchOrderList()
  fetchMeetingRooms()
})

// 获取会议室列表
const fetchMeetingRooms = async () => {
  try {
    const response = await getAllMeetingRooms()
    meetingRooms.value = response.data.list.map(item => ({
      id: item.roomId,
      name: item.name
    }))
  } catch (error) {
    console.error('获取会议室列表失败:', error)
    ElMessage.error('获取会议室列表失败')
  }
}

// 获取订单列表和待付款金额
const fetchOrderList = async () => {
  try {
    const orderResponse = await getOrderList()

    recentOrders.value = orderResponse.data.map(order => ({
      roomName: order.roomName,
      date: order.createdAt,
      time: `${order.startTime} - ${order.endTime}`,
      status: order.status,
      totalCost: order.totalCost
    }))

    const unpaidResponse = await getUnpaidOrderAmount()
    const unpaidAmount = unpaidResponse.data || 0

    // 更新待付款金额统计
    updateStatsData(unpaidAmount)

  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 更新统计数据
const updateStatsData = (unpaidAmount) => {
  statsData.value = statsData.value.map(item => {
    if (item.label === '待付款金额') {
      return {
        ...item,
        value: `¥${parseFloat(unpaidAmount).toFixed(2)}`
      }
    }
    return item
  })
}

// 获取会议室统计
const fetchMeetingRoomStats = async () => {
  try {
    const response = await getAllMeetingRooms()
    const totalRooms = response.data.total || 0

    statsData.value = statsData.value.map((item, index) => {
      if (index === 0) return { ...item, value: totalRooms }
      if (index === 1) return { ...item, value: totalRooms }
      return item
    })

  } catch (error) {
    console.error('获取会议室数据失败:', error)
  }
}

const initChart = () => {
  const chart = echarts.init(usageChart.value)
  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: { type: 'value' },
    series: [{
      name: '使用时长(小时)',
      type: 'bar',
      data: [120, 200, 150, 80, 70, 110, 130],
      itemStyle: { color: '#409EFF' },
      label: {
        show: true,
        position: 'top'
      }
    }]
  }
  chart.setOption(option)

  window.addEventListener('resize', () => chart.resize())
}

const handleQuickBook = async () => {
  try {
    
    if (!quickBookForm.value.roomId ||
      !quickBookForm.value.startTime ||
      !quickBookForm.value.endTime) {
      ElMessage.warning('请填写完整的预订信息')
      return
    }

    const start = new Date(quickBookForm.value.startTime)
    const end = new Date(quickBookForm.value.endTime)

    if (start >= end) {
      ElMessage.warning('结束时间必须晚于开始时间')
      return
    }

    const res = await reserveMeetingroom({
      roomId: quickBookForm.value.roomId,
      startTime: quickBookForm.value.startTime,
      endTime: quickBookForm.value.endTime
    })

    if (res.code === 200) {
      ElMessage.success('预订成功')
      quickBookForm.value = {
        roomId: null,
        startTime: '',
        endTime: ''
      }
      fetchOrderList()
    } else {
      ElMessage.error(res.msg || '预订失败')
    }
  } catch (error) {
    console.error('预订失败:', error)
    ElMessage.error('预订失败，请稍后再试')
  }
}

const goToBooking = () => router.push('/meetingroom/meetingroom')
const goToOrders = () => router.push('/order/order')
</script>

<style scoped lang="scss">
.home {
  .mb-20 {
    margin-bottom: 20px;
  }

  .mt-20 {
    margin-top: 20px;
  }

  .stat-card {
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .card-content {
      display: flex;
      align-items: center;

      .icon-wrapper {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
      }

      .text-wrapper {
        .value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
        }

        .label {
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }

  .function-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-title {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .el-form-item {
      margin-bottom: 20px;

      .el-date-editor {
        width: 100%;
      }
    }

    .el-button {
      width: 15%;
      margin-top: 10px;
    }
  }

  .chart-card {
    margin-top: 20px;

    .header-title {
      font-size: 16px;
      font-weight: bold;
    }
  }
}
</style>